package com.tc.quartz.support.quartz;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import java.lang.reflect.Modifier;

//import javassist.ClassPool;
//import javassist.CtClass;
//import javassist.CtMethod;

//import org.quartz.Job;

/**
 * JOB生成类
 * @author yongjin.ye
 * 
 */
public class JobClassFactory {
	
	protected static Logger log = LoggerFactory.getLogger(JobClassFactory.class);
	

	/**
	 * 静态测试方法
	 */
	/*@SuppressWarnings("rawtypes")
	public static void main(String[] args) throws Exception {
		Class jobClass = JobClassFactory.getClassByName("com.vipshop.userInfo");
		System.out.println(jobClass);
	}*/

	/**
	 * 根据class获取对应的class。
	 * 如果class不存在，则通过字节码生成的方式生成一个class。同时判断class的父类是否为quartz.job.class
	 * @param className
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public synchronized static Class getClassByName(String jobClassName) throws Exception {
		Class jobClass = null;
		try {
			jobClass = JobClassFactory.class.getClassLoader().loadClass(jobClassName);//Class.forName();
		} catch (ClassNotFoundException e) {
			log.error("获取class异常", e);
			//jobClass = GenJobClassByJavassist.makeJobClass(jobClassName);
		}
		// 验证当前class是否为job类
		boolean isQrzJobClass = org.quartz.Job.class.isAssignableFrom(jobClass);
		if (!isQrzJobClass) {
			throw new RuntimeException(String.format("[%s]不是有效的QuartzJob类。", jobClassName));
		}
		return jobClass;
	}

	/**
	 * 动态生成job类
	 * @author yongjin.ye
	 * 
	 */
	static class GenJobClassByJavassist {

		static final String JOB_RUN_MAIN_METHOD = "execute";//doExecute";// job入口方法

		/**
		 * 使用字节码工具Javassist动态生成job类。
		 * @param jobClassName
		 * @return
		 * @throws Exception
		 */
//		@SuppressWarnings("unchecked")
//		public static <T> Class<T> makeJobClass(String jobClassName) throws Exception {
//			ClassPool pool = ClassPool.getDefault();
//			CtClass ctClass = pool.makeClass(jobClassName);
//			ctClass.setInterfaces(new CtClass[] { pool.get(Job.class.getName()) });
//			//ctClass.setInterfaces(new CtClass[] { pool.get(IBaseJobClass.class.getName()) });
//			CtMethod ctMethod = new CtMethod(CtClass.voidType, JOB_RUN_MAIN_METHOD, new CtClass[] {}, ctClass);
//			ctMethod.setModifiers(Modifier.PROTECTED);
//			StringBuffer buffer = new StringBuffer();
//			buffer.append("{\n").append("System.out.println(\"注意：此为自动生成的job任务类，不应该被Quartz执行！\");\n").append("}");
//			ctMethod.setBody(buffer.toString());
//			ctClass.addMethod(ctMethod);
//			// 把生成的class文件写入文件
//			/*byte[] byteArr = ctClass.toBytecode();
//			FileOutputStream fos = new FileOutputStream(new File("D://UserInfo.class"));
//			fos.write(byteArr);
//			fos.close();*/
//			return (Class<T>) ctClass.toClass();
//		}
	}
}
